'use strict';

const db = uniCloud.database()
const coursesCollection = db.collection('courses')
const enrollmentsCollection = db.collection('enrollments')
const ordersCollection = db.collection('orders')

exports.main = async (event, context) => {
	try {
		const { courseId, userInfo } = event
		
		// 参数验证
		if (!courseId || !userInfo) {
			return {
				code: -1,
				msg: '参数不完整',
				data: null
			}
		}
		
		// 检查课程是否存在
		const course = await coursesCollection.doc(courseId).get()
		if (!course.data || course.data.length === 0) {
			return {
				code: -1,
				msg: '课程不存在',
				data: null
			}
		}
		
		// 检查是否已经报名
		// const existingEnrollment = await enrollmentsCollection.where({
		// 	courseId,
		// 	userId: userInfo._id,
			
		// }).get()
		
		// if (existingEnrollment.data && existingEnrollment.data.length > 0) {
		// 	return {
		// 		code: -1,
		// 		msg: '您已经报名过该课程',
		// 		data: null
		// 	}
		// }
		
		// 创建报名记录
		const enrollmentData = {
			courseId,
			userId: userInfo._id,
			userName: userInfo.nickname,
			userAvatar: userInfo.avatar,
			status: 'pending', // pending: 待确认, confirmed: 已确认, cancelled: 已取消
			createTime: Date.now()
		}
		
		await enrollmentsCollection.add(enrollmentData)
		
		// 创建订单记录
		const orderData = {
			courseId,
			courseName: course.data[0].name, // 课程名称
			userId: userInfo._id,
			userName: userInfo.nickname,
			userAvatar: userInfo.avatar,
			status: 'pending', // 订单状态：pending-待支付，paid-已支付，cancelled-已取消
			amount: course.data[0].price || 0, // 课程价格
			createTime: Date.now(),
			updateTime: Date.now()
		}
		
		await ordersCollection.add(orderData)
		
		// 更新课程报名人数
		await coursesCollection.doc(courseId).update({
			enrollmentCount: db.command.inc(1)
		})
		
		return {
			code: 0,
			msg: '报名成功',
			data: null
		}
	} catch (error) {
		console.error('报名失败', error)
		return {
			code: -1,
			msg: '报名失败',
			data: null
		}
	}
} 